package user.controllers;

import helpers.EmailHelper;
import helpers.IdUniqueHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import search.ArticleSearchEngine;
import systems.Recently;
import user.models.ArticleModel;

import entities.ApplicationConfig;
import entities.Article;
import entities.ArticleSearch;
import entities.Category;
import entities.User;

public class ArticleDeleteServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String param = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		String[] params = param.split("/");
		
		String id = params[0];
		String authKey = "";
		if (params.length > 1) {
			authKey = params[1];
		}
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		User user = (User) request.getAttribute("user_logged_in");
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = (Article) articleModel.getArticle(appConfig.getApplicationId(), id);
		
		if (article == null || !article.getAuthKey().equals(authKey)) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		if (article != null) {
			articleModel.delete(appConfig.getApplicationId(), article);
			
			//Set search article
			ArticleSearchEngine.remove(id);
			
			//Remove recently cache
			Recently.remove(appConfig.getApplicationId(), article);
			
			//Remove cache list
			//articleModel.removeListCache(appConfig.getApplicationId(), article);
			
			//remove cache my article
			articleModel.removeCacheMyArticle(appConfig.getApplicationId(), article.getCreator(), language);
			
			article = null;
			
			//request.setAttribute("success", "Article has been removed!");
			response.sendRedirect("/profile/article/list");
			return;
		}
	}
}
